using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Character : MonoBehaviour
{
    protected Player player;
    private Renderer playerRenderer;
    private Color originalColor;
    void Start()
    {
        
        player = GetComponent<Player>();
        playerRenderer = GetComponent<Renderer>();
        if (playerRenderer != null)
        {
            originalColor = playerRenderer.material.color; // 保存原始颜色
        }
    }
    
//人物受伤
    public virtual void TakeDamage(float _damage)
    {
        float actualDamage = _damage * (1-Mathf.Min(player.stats.defense * 0.01f, 0.90f)) * player.stats.PlayerDamageMultiplier;

        if (player.stats.shield > 0)
        {
            player.stats.shield -= actualDamage;
            if (player.stats.shield < 0)
            {
                actualDamage = -player.stats.shield;
                player.stats.shield = 0;
            }
            else
            {
                actualDamage = 0;
            }
        }

        if (actualDamage > 0)
        {
            if (player.stats.invulnerable) //在无敌时不造成伤害
                return;

            player.stats.health -= actualDamage;
            StartCoroutine(InvulerableCoroutine()); //启动无敌
            StartCoroutine(FlashRed()); // 启动红色闪烁效果
        }

        if (player.stats.health <= 0f)
        {
            //死亡
            Die();
        }
    }

//人物死亡
    private void Die()
    {
        player.stats.health = 0f;
        Destroy(this.gameObject);//销毁对象
    }
//无敌
    IEnumerator InvulerableCoroutine()
    {
        player.stats.invulnerable = true;
        //等待无敌时间
        yield return new WaitForSeconds(player.stats.invulerableDuration);
        player.stats.invulnerable = false;
    }
 // 红色闪烁效果
 IEnumerator FlashRed()
 {
     if (playerRenderer != null)
     {
         for (int i = 0; i < 3; i++) // 闪烁次数
         {
             playerRenderer.material.color = Color.red; // 设置为红色
             yield return new WaitForSeconds(0.1f); // 等待0.1秒
             playerRenderer.material.color = originalColor; // 恢复原始颜色
             yield return new WaitForSeconds(0.1f); // 等待0.1秒

         }
     }
 }
}
